﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using EPiServer.Core;
using System.Collections.Generic;
using System.Collections.Specialized;


namespace EPiServer.Research.UI.CssEditor.Ajax
{
    public partial class StyleManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            // some security check
            if (!EPiServer.Security.PrincipalInfo.HasEditAccess)
                return;

            if (Request["pageid"] == string.Empty)
                return;
            
            int pageid = int.Parse(Request["pageid"]);

            try
            {
                EPiServer.DataFactory.Instance.GetPage(new PageReference(pageid));                
            }
            catch (Exception exp)
            {
                return;
            }

            if (Request["removemodifications"] == "true")
            {
                CssDB.saveSetting(pageid,new string[]{},new string[]{});
                return;
            }
            string csss = Request["css"];

            // remove last $
            if (csss.EndsWith("$"))
                csss = csss.Substring(0, csss.Length - 1);

            string[] cssArray = csss.Split(new char[] { '$' });
            string[] rulenames = new string[cssArray.Length];
            string[] rulevalues = new string[cssArray.Length];
            int j = 0;
            foreach (string css in cssArray)
            {
                string[] pairvalue = css.Split(new char[] {'@' });
                
                string cssname = pairvalue[0];
                string cssstring = pairvalue[1];
                rulenames[j]=cssname;
                rulevalues[j]=cssstring;
                j++;
            }
            CssDB.saveSetting(pageid, rulenames,rulevalues);
        }
    }
}
